package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       /*
        0、拦截所有请求  /*
        1、资源放行：登录相关的、退出登录相关的、静态资源【html、css 、js 、图片】
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**" };
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match(表达式, 具体的uri路径);
        2、判断是否登录：依据是什么？  session中的用户信息！！
            2.1、如果是登录过的：放行
            2.2、如果没有登录：不放行，跳转【重定向】登录页
        */
        String[] loginUrls = {
                "/user/login",
                "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**" };
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getRequestURI();// /employee/login  /backend/index.html
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if(match) {
                chain.doFilter(req, resp);
                return;
            }
        }
        HttpSession session = request.getSession();
        Employee loginEmployee = (Employee) session.getAttribute("loginEmployee");
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginEmployee!=null || loginUser!=null){
            //登录成功，向ThreadLocal存入当前用户
            if(loginEmployee !=null){
                UserHolder.setUser(loginEmployee);
            }
            if(loginUser!=null){
                UserHolder.setUser(loginUser);
            }

            chain.doFilter(req, resp);//放行

            //回来的代码，需要释放ThreadLocal中存储的用户，避免内存溢出的风险。
            UserHolder.release();
        }else {//未登录
            HttpServletResponse response = (HttpServletResponse) resp;
            R<Object> notlogin = R.error("NOTLOGIN");
            String jsonString = JSON.toJSONString(notlogin);
            response.getWriter().write(jsonString);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
